﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Timers;
 
namespace wifi_test
{
    public partial class MainForm : Form
    {
        public enum recordstate { nouse, recerror, senderror, endtest, starttest };
        public enum xmlevnet { start, end, error, testdata };
        cls_record record_cls;
        cls_XML recordXML_cls = new cls_XML();
        cls_net net_cls;

        Thread udpRecThread;
        Thread udpSendThread;
        Thread udpRecThreadTest;

        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error, Custom, Receve };
        public Color[] LogMsgTypeColor = { Color.Orange, Color.Green, Color.Black, Color.Brown, Color.Red, Color.Yellow, Color.Blue };
        private object lockForWrite = new object();
        public enum TestState { idle, handshake, testing, sendhandshake, getdstinfo };
        TestState runState = TestState.idle;
        int dispTime;

        int rec_speed;
        int send_speed;

        public System.Timers.Timer runTimeOverTimer;
        public System.Timers.Timer dispLogTimer;

        #region 这部份是多目标机测试部份

        private int _LocalMainRecPort;  //用于记录下本机主接收端口
        cls_testnet [] _testnetCls_array; //多目标测试对象组

        #endregion

        //以下是5组数据列表
        GroupBox xuGroupBox;///[5]; 
        TextBox [] xuTextBox_array;  
        Label [] xuLable_array; 

        private bool _isRuning = false;
        private bool _isHandshak = false;

        private static Semaphore _lockthread;   //用于锁定线程的信号

        public MainForm()
        {
            InitializeComponent();

            #region 窗体控件的初始化
            //窗体控件的初始化部份
            comboBox1.Items.Clear();
            comboBox1.Items.Add("单目标机连续测试");
            comboBox1.Items.Add("多目标机连续测试");
            comboBox1.Items.Add("指定测试次数");
            comboBox1.SelectedIndex = 0;

            String xustr = System.Net.Dns.GetHostName();

            System.Net.IPAddress addr;

            // 获得本机局域网IP地址

            addr = new System.Net.IPAddress(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].Address);
            xustr = addr.ToString();

            localIp_TextBox.Text = xustr;
            runTimeOverTimer = new System.Timers.Timer();
            runTimeOverTimer.AutoReset = false;
            runTimeOverTimer.Elapsed += new ElapsedEventHandler(runTimeOverTimer_Elapsed);

            dispLogTimer = new System.Timers.Timer();
            dispLogTimer.AutoReset = false;
            dispLogTimer.Elapsed += new ElapsedEventHandler(dispLogTimer_Elapsed);

            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_Closing);

            dispTime = trackBar1.Value;

            net_cls = new cls_net(this);
            record_cls = new cls_record();

            _lockthread = new Semaphore(1, 1);

            statusTools.Items[0].Text = "准备开始测试";
            statusTools.Items[1].Text = "";

            record_cls.sub_setMF(this);

            recordXML_cls.fun_InitXML();

            #region 读取配置文件

            cls_ReadSetup xuReadSetup = new cls_ReadSetup();

            if (xuReadSetup.fun_SetupFileExist())
            {
                
            }

            #endregion

            #endregion
        }


        /// <summary>
        /// 关闭窗口时发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (runState == TestState.testing)
            {
                recordXML_cls.fun_WirteXML(xmlevnet.end, System.DateTime.Now.ToString(), null);
            }

        }
       

        /// <summary>
        /// 初始化完后与下位机进行握手
        /// </summary>
        /// 1、向下位机发送are you ready信息
        /// 2、下位机接收到are you ready信息后，向上位机发送ok帧
        /// 3、上位机接收到ok帧后认为握手成功
        /// <returns></returns>
        private bool fun_ReadyStartTest()
        {
            bool retflag;
            string xustr = "ready?";

            //以下要启动接收线程了
            udpRecThread = new Thread(new ParameterizedThreadStart(this.recThread));
            udpRecThread.IsBackground = true;

            //以下是要准备发送线程，但不启动
            if (checkBox1.CheckState != CheckState.Checked)
            {
                udpSendThread = new Thread(new ParameterizedThreadStart(this.sendThread));
                udpSendThread.IsBackground = true;
            }
            else
            {
                udpRecThreadTest = new Thread(new ParameterizedThreadStart(this.testThread));
                udpRecThreadTest.IsBackground = true;
            }

            if (runState != TestState.sendhandshake)
            {

                byte[] data_sp = new byte [32];
                Array.Copy(System.Text.Encoding.Default.GetBytes(xustr), data_sp, 6);
                //data_sp = System.Text.Encoding.Default.GetBytes(xustr);
                // = new byte[] { 'a', 1, 2, 3, 4, 5 }; 

                net_cls.sub_SendFrame(data_sp);

                runTimeOverTimer.Enabled = false;
                runTimeOverTimer.Interval = 1000 * 6; //6秒
                runTimeOverTimer.Enabled = true;

                udpRecThread.Start(0);

                retflag = true;

                runState = TestState.handshake;
            }
            else
            {
                udpRecThread.Start(0);
                retflag = true;
            }

            return retflag;
        }



        /// <summary>
        /// 开始测试按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            bool retflag;

            if (_isRuning == false)
            {
                checkBox1.Enabled = false;

                if (_moreDest != 0)
                {
                    //进行多目标机的测试
                    _LocalMainRecPort = Convert.ToInt32(localport_text.Text);
                    _testnetCls_array = new cls_testnet[_moreDest];

                    IPEndPoint tmpPoint;
                    IPAddress tmpAddress;
                    int tmpPort;

                    for (int i = 0; i < _moreDest; i++)
                    {
                        tmpAddress  = System.Net.IPAddress.Parse(xuTextBox_array[i * 2 + 1].Text);  //目标的IP地址
                        tmpPort = Convert.ToInt32(xuTextBox_array[i * 2 + 1 + 1].Text); //目标的端口
                        tmpPoint = new IPEndPoint(tmpAddress, tmpPort);

                        _testnetCls_array[i] = new cls_testnet(this, tmpPoint, _LocalMainRecPort + i * 2, _LocalMainRecPort + i * 2);
                        _testnetCls_array[i].sub_StartThread();
                    }

                    button2.Text = "停止测试";
                    _isRuning = true;

                }
                else
                {

                    try
                    {
                        retflag = net_cls.fun_InitSendInterface(dstip_text.Text, Convert.ToInt32(dstport_text.Text));
                    }
                    catch (Exception xe)
                    {
                        Console.WriteLine("The process failed: {0}", xe.ToString());
                        checkBox1.Enabled = true;
                        return;
                    }

                    if (retflag == false)
                    {
                        checkBox1.Enabled = true;
                        return;
                    }


                    try
                    {
                        retflag = net_cls.fun_InitRecInterface(localIp_TextBox.Text, Convert.ToInt32(localport_text.Text));
                    }
                    catch (Exception xe)
                    {
                        Console.WriteLine("The process failed: {0}", xe.ToString());
                        checkBox1.Enabled = true;
                        return;
                    }

                    if (retflag == false)
                    {
                        checkBox1.Enabled = true;
                        return;
                    }

                    IPAddress tmp_address;

                    tmp_address = System.Net.IPAddress.Parse(dstip_text.Text);
                    IPEndPoint tmp_endpoint = new IPEndPoint(tmp_address, Convert.ToInt32(dstport_text.Text) + 1);
                    record_cls.sub_setCmdPoint(tmp_endpoint);

                    tmp_endpoint.Address = System.Net.IPAddress.Parse(localIp_TextBox.Text);
                    tmp_endpoint.Port = Convert.ToInt32(localport_text.Text) + 1;
                    record_cls.datPoint = tmp_endpoint;

                    string str = System.DateTime.Now.ToString();
                    xulog(LogMsgType.Incoming, "准备开始进行测试" + "\n");

                    retflag = fun_ReadyStartTest();
                    rec_speed = 0;
                    send_speed = 0;
                    button2.Text = "停止测试";
                    _isRuning = true;
                    statusTools.Items[0].Text = "";

                    record_cls.dstSystemRecCount = 0;
                    record_cls.dstSystemSendCount = 0;
                    record_cls.dstRecCount = 0;
                    record_cls.dstSendCount = 0;
                }
            }
            else
            {
                sub_stoptest(0);
            }

        }


        /// <summary>
        /// 接收UDP的线程
        /// </summary>
        /// <param name="param"></param>
        public void recThread(Object param)
        {
            byte[] recbuf = null;
            int i;

            while (true)
            {
                recbuf = net_cls.fun_RecDstData();
                if (recbuf != null)
                {
                    i = net_cls.fun_AnalyFrame(recbuf, runState);
                    if (i == 100)
                    {
                        //表示握手成功了
                        runState = TestState.testing;
                        runTimeOverTimer.Enabled = false;  //停止主定时器
                        if (checkBox1.CheckState != CheckState.Checked)
                        {
                            udpSendThread.Start(0);

                            if (dispTime == 0)
                            {
                                dispTime = 1;
                            }
                            dispLogTimer.Interval = dispTime * 60 * 1000;
                            dispLogTimer.Enabled = true;
                        }
                        else
                        {
                            udpRecThreadTest.Start(0);
                        }
                        xulog(LogMsgType.Incoming, "握手成功！！！" + "\n");
                        recordXML_cls.fun_WirteXML(xmlevnet.start, System.DateTime.Now.ToString(), null);
                        //record_cls.sub_recordin(MainForm.recordstate.starttest, " ");
                        net_cls.sub_SetRecFrameNo(-1);
                        net_cls.recErrors = 0;
                    }
                }
                else
                {
                    if (runState == TestState.testing)
                    {
                        sub_stoptest(1);
                        return;
                    }
                }
            }
        }


        /// <summary>
        /// 发送UDP的线程
        /// </summary>
        /// <param name="param"></param>
        public void sendThread(Object param)
        {
            int i;
            byte[] sendbuf;

            i = net_cls.sendPackets;
            while (true)
            {
                _lockthread.WaitOne();

                #region 这段代码被_lockthread所保护

                if (i > 9)
                {
                    i = i % 10;
                }

                sendbuf = net_cls.fun_CreateFrame(Convert.ToByte(i));
                if (sendbuf != null)
                {
                    net_cls.sub_SendFrame(sendbuf);
                    //Thread.Sleep(1);   //停下10ms
                    //Thread.Sleep(1);       
                }
                i += 1;
                net_cls.sendPackets = net_cls.sendPackets + 1;

                #endregion

                _lockthread.Release();
            }
        }

        public delegate void CLog(LogMsgType msgtype, string msg);

        /// <summary>
        /// 日志记录方法
        /// </summary>
        /// <param name="msgtype">字体颜色</param>
        /// <param name="msg">文字消息</param>
        /// <param name="flag">字体颜色</param>
        public void Log(LogMsgType msgtype, string msg)
        {
            lock (lockForWrite)
            {

                if (!testInfo.InvokeRequired)
                {
                    if (testInfo.Lines.Length > 1000)
                    {
                        testInfo.Clear();
                    }
                    testInfo.SelectedText = string.Empty;
                    testInfo.SelectionFont = new Font(testInfo.SelectionFont, FontStyle.Bold);
                    testInfo.SelectionColor = LogMsgTypeColor[(int)msgtype];
                    testInfo.AppendText(msg);
                    testInfo.ScrollToCaret();
                }
                else
                {
                    CLog _Log = new CLog(Log);
                    testInfo.BeginInvoke(_Log, new object[] { msgtype, msg });
                }
            }
        }


        /// <summary>
        /// 运行时的主超时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void runTimeOverTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            System.Timers.Timer handleTimer = (System.Timers.Timer)sender;

            runTimeOverTimer.Enabled = false;
            switch (runState)
            {
                case TestState.handshake:
                    //握手时发生的超时
                    xulog(LogMsgType.Error, "握手发生超时......" + "\n");

                    string xustr = "ready?";

                    byte[] data_sp = System.Text.Encoding.Default.GetBytes(xustr);
                    // = new byte[] { 'a', 1, 2, 3, 4, 5 }; 

                    net_cls.sub_SendFrame(data_sp);

                    runTimeOverTimer.Interval = 6 * 1000;
                    runTimeOverTimer.Enabled = true;
                    break;

                case TestState.getdstinfo:
                    //获取目标机信息时超时
                    net_cls.sub_CloseTempRecBlock();
                    handleTimer.Enabled = false;
                    //xulog(LogMsgType.Error, "出错！！！出错！！！出错！！！" + "\n");
                    break;
            }
        }


        /// <summary>
        /// 显示日志内容的定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void dispLogTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            int ret = -1;
            int trycount = 0;
            string xmlstr;

            //System.Timers.Timer handleTimer = (System.Timers.Timer)sender;

            dispLogTimer.Enabled = false;

            _lockthread.WaitOne();

            #region 以下代码被_lockthread保护

            System.Timers.Timer getInfoTimer = new System.Timers.Timer(3 * 1000);
            getInfoTimer.Elapsed += new ElapsedEventHandler(getInfoTimer_Elapsed);
            getInfoTimer.AutoReset = false;
            
            while (trycount < 3)
            {
                getInfoTimer.Enabled = true;        //启动这个定时器
                ret = record_cls.fun_GetDestInfo();
                getInfoTimer.Enabled = false;
                getInfoTimer.Interval = 3 * 1000;
                if (ret == -1)
                {
                    trycount += 1;
                }
                else
                {
                    break;
                }
            }

            //ret = record_cls.fun_GetDestInfo();
            //getInfoTimer.Enabled = false;
            //getInfoTimer.Elapsed -= new ElapsedEventHandler(getInfoTimer_Elapsed);
            getInfoTimer.Close();
            //xulog(LogMsgType.Error, "getDestInfo ret！！！" + "\n");

            if (ret != -1)
            {
                //没有取到目标设备上送的实际的数据
                xmlstr = "driver_rec:" + record_cls.dstRecCount.ToString() + "-" + "driver_send:" + record_cls.dstSendCount.ToString() + "-";
                xmlstr += "system_rec:" + record_cls.dstSystemRecCount.ToString() + "-" + "system_send:" + record_cls.dstSystemSendCount.ToString();
                xmlstr += "-" + "local_rec:" + net_cls.recPackets.ToString() + "-" + "local_send:" + net_cls.sendPackets.ToString();
            }
            else
            {
                //要把数据记录到xml中去了
                xmlstr = "local_rec:" + net_cls.recPackets.ToString() + "-" + "local_send:" + net_cls.sendPackets.ToString();
            }
           
            runState = TestState.testing;
            uint i = (uint)net_cls.sendPackets;
            uint j = (uint)net_cls.recPackets;

            string xustr = "发送了" + i.ToString() + "包" + "--接收了" + j.ToString() + "包";
            xustr += "--接收发错了" + net_cls.recErrors.ToString() + "包" + "--发送出错了" + net_cls.sendErrors.ToString() + "包"
                     + "--掉失" + net_cls.recMiss.ToString();
            //string xustr = "111111";
            xulog(LogMsgType.Incoming, xustr + "\n");

            uint x, z;

            int tmp_speed = (((int)i - send_speed) * 1021) / 60;
            int tmp_rec = (((int)j - rec_speed) * 1021) / 60;

            rec_speed = (int)j;
            send_speed = (int)i;
            
            statusTools.Items[0].Text = "接收速率：" + tmp_speed.ToString() + " bytes/s";
            statusTools.Items[1].Text = "发送速率：" + tmp_rec.ToString() + " bytes/s";


            if (i > 1024 * 10)
            {
                x = ((i / 1024) * 1021) / 1024;
            }
            else
            {
                x = (i * 1021) / (1024 * 1024);
            }

            if (j > 1024 * 10)
            {
                z = ((j / 1024) * 1021) / 1024;
            }
            else
            {
                z = (j * 1021) / (1024 * 1024);
            }
            string xustr1 = "发送" + x.ToString() + "M的数据" + "--接收了" + z.ToString() + "M的数据" + "\n";
            xulog(LogMsgType.Outgoing, xustr1);

            recordXML_cls.fun_WirteXML(xmlevnet.testdata, System.DateTime.Now.ToString(), xmlstr);
            dispLogTimer.Interval = dispTime * 60 * 1000;
            dispLogTimer.Enabled = true;

            #endregion
           
            _lockthread.Release();
        }


        /// <summary>
        /// 在记录的信息前加入，事件发生的时间
        /// </summary>
        /// <param name="msgtype"></param>
        /// <param name="msg"></param>
        public void xulog(LogMsgType msgtype, string msg)
        {
            string newstr = System.DateTime.Now.ToString() + "--" + msg;
            Log(msgtype, newstr);
        }

        /// <summary>
        /// 日志显示时间的设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trackBar1_Scroll(object sender, EventArgs e)
        {            
            int i = trackBar1.Value;

            dispTime = i;

            label7.Text = i.ToString() + "分钟";
        }


        //public delegate void CStopTest();
        /// <summary>
        /// 停止测试
        /// </summary>
        /// flag为0表示要关闭两个线程
        /// flag为1表示要关闭发送线程
        /// flag为2表示要关闭接收线程
        public void sub_stoptest(int flag)
        {
            xulog(LogMsgType.Incoming, "停止测试" + "\n");
            _isRuning = false;

            if (_moreDest != 0)
            {
                for (int j = 0; j < _moreDest; j++)
                {
                    _testnetCls_array[j] = null;
                }
                _testnetCls_array = null;
                //GC.Collect();
            }
            else
            {

                _lockthread.WaitOne();

                if (flag == 0)
                {
                    if (udpRecThread.IsAlive)
                    {
                        udpRecThread.Abort();
                    }
                    if (checkBox1.CheckState != CheckState.Checked)
                    {
                        if (udpSendThread.IsAlive)
                        {
                            try
                            {
                                udpSendThread.Abort();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.ToString());
                            }
                        }
                    }
                    else
                    {
                        udpRecThreadTest.Abort();
                    }
                }
                else if (flag == 1)
                {
                    if (checkBox1.CheckState != CheckState.Checked)
                    {
                        if (udpSendThread.IsAlive)
                        {
                            udpSendThread.Abort();
                        }
                    }
                    else
                    {
                        udpRecThreadTest.Abort();
                    }
                }
                else if (flag == 2)
                {

                    if (udpRecThread.IsAlive)
                    {
                        udpRecThread.Abort();
                    }
                }

                _lockthread.Release();
                //runState = TestState.idle;
                net_cls.sub_reinit();
                runTimeOverTimer.Enabled = false;
                dispLogTimer.Enabled = false;

                uint i = (uint)net_cls.sendPackets;
                uint j = (uint)net_cls.recPackets;

                xulog(LogMsgType.Warning, "--------------------\n");
                string xustr = "发送了" + i.ToString() + "包" + "--接收了" + j.ToString() + "包";
                xustr += "--接收发错了" + net_cls.recErrors.ToString() + "包" + "--发送出错了" + net_cls.sendErrors.ToString() + "包" +
                          "--掉失" + net_cls.recMiss.ToString();
                //string xustr = "111111";
                xulog(LogMsgType.Incoming, xustr + "\n");

                uint x, z;

                if (i > 1024 * 10)
                {
                    x = ((i / 1024) * 1021) / 1024;
                }
                else
                {
                    x = (i * 1021) / (1024 * 1024);
                }

                if (j > 1024 * 10)
                {
                    z = ((j / 1024) * 1021) / 1024;
                }
                else
                {
                    z = (j * 1021) / (1024 * 1024);
                }
                string xustr1 = "发送" + x.ToString() + "M的数据" + "--接收了" + z.ToString() + "M的数据" + "\n";
                xulog(LogMsgType.Outgoing, xustr1);
                xulog(LogMsgType.Warning, "--------------------\n");

                //cls_net.record_cls.sub_recordin(cls_record.recordstate.endtest, "--总共发送了" + i.ToString() + "--总共接收了" 
                //                                + j.ToString() + "--接收出错" + cls_net.sendErrors.ToString() + "--掉失" + cls_net.recMiss.ToString());
                //record_cls.sub_recordin(MainForm.recordstate.endtest, "--总共发送了" + i.ToString() + "--总共接收了"
                //                                + j.ToString() + "--接收出错" + cls_net.sendErrors.ToString());

                if (runState == TestState.testing)
                {
                    recordXML_cls.fun_WirteXML(xmlevnet.end, System.DateTime.Now.ToString(), null);
                }

                runState = TestState.idle;
            }
            sub_modbuttontext("开始测试");
        }


        /// <summary>
        /// 用于托管的修改开始测试的text
        /// </summary>
        /// <param name="msg"></param>
        public delegate void CStartText(string msg);
        public void sub_modbuttontext(string msg)
        {
            if (!button2.InvokeRequired)
            {
                button2.Text = msg;
                //record_cls.sub_genrecordfile();
                checkBox1.Enabled = true;
                statusTools.Items[0].Text = "准备开始测试";
                statusTools.Items[1].Text = "";
            }
            else
            {
                CStartText _Log = new CStartText(sub_modbuttontext);
                testInfo.BeginInvoke(_Log, msg);
            }
        }


        /// <summary>
        /// 用于PC对测的选项的改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.CheckState == CheckState.Checked)
            {
                runState = TestState.sendhandshake;
            }
            else
            {
                runState = TestState.idle;
            }
        }


        /// <summary>
        /// 把事件记录到cls_record类中去
        /// </summary>
        /// <param name="xulog">事件信息</param>
        /// <param name="eventstate">事件的类型</param>
        /// 作者：xhd
        /// 修改：
        public void sub_enterlog(MainForm.recordstate eventstate, string xulog)
        {
            //record_cls.sub_recordin(eventstate, xulog);
        }


        /// <summary>
        /// 主窗体向外部提供的发送数据的接口
        /// </summary>
        /// <param name="data">要发送的数据</param>
        /// <param name="tmp_point">要发送到的目的地</param>
        /// 作者:xhd
        /// 建立时间:09.10.20
        public void sub_sendData(byte[] data, IPEndPoint tmp_point)
        {
            net_cls.sub_xxSendFrame(data, tmp_point);
        }


        /// <summary>
        /// 主窗体向外部提供的接收数据的接口
        /// </summary>
        /// <param name="tmp_point">指定的端口</param>
        /// <returns>接收到的数据，null表示失败了</returns>
        /// 作者:xhd
        /// 建立时间:09.10.20
        public byte[] fun_recTmpData(IPEndPoint tmp_point)
        {
            return net_cls.fun_GetDestInfo(tmp_point);
        }



        /// <summary>
        /// 测试用的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            cls_XML xutest = new cls_XML();

            xutest.fun_InitXML();
            xutest.fun_WirteXML(xmlevnet.testdata, "123455", "aaaa:1111-bbbb:2222-cccc:3333-dddd:4444-eeee:5555-ffff:6666");
        }


        /// <summary>
        /// 取得目标设备的测试信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void getInfoTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            System.Timers.Timer handleTimer = (System.Timers.Timer)sender;

            handleTimer.Enabled = false;
            net_cls.sub_CloseTempRecBlock();
            //xulog(LogMsgType.Error, "出错！！！出错！！！出错！！！" + "\n");
        }


        /// <summary>
        /// 关闭net_cls类中的临时udpclient
        /// </summary>
        /// 作者:xhd
        /// 创建时间:09.10.20
        public void sub_closeTmpUdpClient()
        {
            net_cls.sub_CloseTempRecBlock();
        }


        /// <summary>
        /// 进行PC对测时，做为从机用于接收命令端口的数据线程
        /// </summary>
        /// <param name="param"></param>
        /// 作者:xhd
        /// 创建时间:09.10.28
        public void testThread(Object param)
        {
            IPAddress tmp_address;
  
            tmp_address = System.Net.IPAddress.Parse(localIp_TextBox.Text);

            IPEndPoint tmp_point = new IPEndPoint(tmp_address, Convert.ToInt32(localport_text.Text) + 1);
            while (true)
            {
                byte[] recbuf = net_cls.fun_GetDestInfo(tmp_point);
                if (recbuf != null)
                {
                    string xustr = System.Text.Encoding.Default.GetString(recbuf);
                    if (xustr.Contains("command"))
                    {
                        int i = net_cls.recPackets;
                        xulog(LogMsgType.Incoming, "接收到的包数为：" + i.ToString() + "\n");

                        byte[] sendbuf = new byte[20];
                        for (int j = 0; j < 20; j++)
                        {
                            sendbuf[j] = 0;
                        }
                       
                        sendbuf[4] = Convert.ToByte((i >> 24) & 0xff);
                        sendbuf[5] = Convert.ToByte((i >> 16) & 0xff);
                        sendbuf[6] = Convert.ToByte((i >> 8) & 0xff);
                        sendbuf[7] = Convert.ToByte((i & 0xff));
                        tmp_address = System.Net.IPAddress.Parse(dstip_text.Text);
                        tmp_point = new IPEndPoint(tmp_address, Convert.ToInt32(dstport_text.Text) + 1);
                        net_cls.sub_xxSendFrame(sendbuf, tmp_point);

                        tmp_address = System.Net.IPAddress.Parse(localIp_TextBox.Text);

                        tmp_point = new IPEndPoint(tmp_address, Convert.ToInt32(localport_text.Text) + 1);
                    }
                    net_cls.sub_CloseTempRecBlock();
                }
            }
        }


        /// <summary>
        /// 选择测试方式被按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        int _moreDest = 0;
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string str = comboBox1.SelectedItem.ToString();
            int ret = string.Compare(str, "多目标机连续测试");
            if (ret == 0)
            {
                //要开始重新布局
                xuGroupBox = new GroupBox();
                xuGroupBox.Text = "多目标机设置";
                groupBox1.Visible = false;
                xuGroupBox.SuspendLayout();
                xuGroupBox.Location = new System.Drawing.Point(12, 128);
                xuGroupBox.Name = "groupBox_xu1";
                xuGroupBox.Size = new System.Drawing.Size(310, 52);
                xuGroupBox.ResumeLayout(false);
                xuGroupBox.PerformLayout();
                xuGroupBox.Visible = true;
                this.Controls.Add(xuGroupBox);

                xuLable_array = new Label[6 + 1];
                xuTextBox_array = new TextBox[6 + 1];

                xuLable_array[0] = new Label();
                xuLable_array[0].Text = "目标机数：";
                xuLable_array[0].AutoSize = true;
                xuLable_array[0].Location = new System.Drawing.Point(6, 23);
                //xuLable_array[0].Name = "xulabel";
                xuLable_array[0].Size = new System.Drawing.Size(65, 12);
                xuGroupBox.Controls.Add(xuLable_array[0]);

                xuTextBox_array[0] = new TextBox();
                //xuTextBox_array[0].Text = "目标机数：";
                xuTextBox_array[0].AutoSize = true;
                xuTextBox_array[0].Location = new System.Drawing.Point(xuLable_array[0].Width + 10, 20);
                xuTextBox_array[0].Name = "xuDstNumText";
                xuTextBox_array[0].Size = new System.Drawing.Size(30, 12);
                xuGroupBox.Controls.Add(xuTextBox_array[0]);

                xuTextBox_array[0].TextChanged += new EventHandler(MainForm_TextChanged);
                return;
            }

            ret = string.Compare(str, "单目标机连续测试");
            if (ret == 0)
            {
                if (_moreDest == 0)
                {
                    groupBox1.Visible = true;
                }
                else
                {

                    xuLable_array[0] = null;
                    xuTextBox_array[0] = null;
                    for (int i = 0; i < _moreDest; i++)
                    {
                        xuLable_array[1 + i] = null;
                        xuTextBox_array[1 + i] = null;
                    }
                    xuTextBox_array = null;
                    xuLable_array = null;
                    groupBox1.Visible = true;
                    xuGroupBox.Visible = false;
                    xuGroupBox = null;
                }
            }
        }


        /// <summary>
        /// 关于多目标测试时多个目标值输入时的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MainForm_TextChanged(object sender, EventArgs e)
        {
            TextBox tmpTextBox = (TextBox)sender;

            if (tmpTextBox.Name == "xuDstNumText")
            {
                int i = Convert.ToInt32(tmpTextBox.Text);
                if (i == 0)
                {
                    i = 1;
                }
                if (i > 3)
                {
                    return;
                }
                if (i != _moreDest)
                {
                    if (_moreDest != 0)
                    {
                        for (int j = 0; j < _moreDest * 2; j++)
                        {
                            xuTextBox_array[1 + j] = null;
                            xuLable_array[1 + j] = null;
                        }
                    }
                    _moreDest = i;
                    int x, y;

                    x = xuLable_array[0].Left;
                    y = xuTextBox_array[0].Height + xuTextBox_array[0].Top + 10;
                    //xuTextBox_array[0].Visible = false;
                    //xuLable_array[0].Visible = false;
                    for (int j = 0; j < i * 2; j += 2)
                    {
                        xuTextBox_array[1 + j] = new TextBox();
                        xuLable_array[1 + j] = new Label();
                        xuTextBox_array[1 + j + 1] = new TextBox();
                        xuLable_array[1 + j + 1] = new Label();

                        xuLable_array[1 + j].Text = "目标IP：";
                        xuLable_array[1 + j].AutoSize = true;
                        xuLable_array[1 + j].Location = new System.Drawing.Point(x, y);
                        //xuLable_array[0].Name = "xulabel";
                        xuLable_array[1 + j].Size = new System.Drawing.Size(65, 12);
                        xuGroupBox.Controls.Add(xuLable_array[1 + j]);

                        xuTextBox_array[1 + j].Location = new System.Drawing.Point(xuLable_array[1 + j].Width + 10, y - 5);
                        xuTextBox_array[1 + j].Size = new System.Drawing.Size(112, 12);
                        xuGroupBox.Controls.Add(xuTextBox_array[1 + j]);

                        xuLable_array[1 + j + 1].Text = "端口号：";
                        xuLable_array[1 + j + 1].AutoSize = true;
                        xuLable_array[1 + j + 1].Location = new System.Drawing.Point(xuTextBox_array[1 + j].Left + xuTextBox_array[1 + j].Width + 10, y);
                        //xuLable_array[0].Name = "xulabel";
                        xuLable_array[1 + j].Size = new System.Drawing.Size(65, 12);
                        xuGroupBox.Controls.Add(xuLable_array[1 + j + 1]);

                        xuTextBox_array[1 + j + 1].Location = new System.Drawing.Point(xuLable_array[1 + j + 1].Left + xuLable_array[1 + j + 1].Width + 5, y - 5);
                        xuTextBox_array[1 + j + 1].Size = new System.Drawing.Size(50, 12);
                        xuGroupBox.Controls.Add(xuTextBox_array[1 + j + 1]);

                        y += xuTextBox_array[1 + j].Height + 10;
                        xuGroupBox.Height += xuTextBox_array[1 + j].Height + 10;
                    }
                }
            }
        }


    }
}
